package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.CommonConstant;
import com.itheima.common.Result;
import com.itheima.entity.User;
import com.itheima.service.IUserService;
import com.itheima.util.JwtUtil;
import com.itheima.util.PasswordUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sys")
@Validated
public class LoginController {

    @Autowired
    private IUserService userService;
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$",message = "需要5-16位字符") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = userService.getOne(queryWrapper);
        if (user == null){
            return Result.error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500,"该用户不存在，请注册");
        }
        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(username, password, user.getSalt());
        String syspassword = user.getPassword();
        if (!syspassword.equals(userpassword)) {
            return Result.error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500,"用户名或密码错误");
        }
        String token = JwtUtil.sign(username, syspassword);
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token,token,1, TimeUnit.MINUTES);
        return Result.OK("登录成功",token);
    }

}
